package net.xdclass.xdclass_shiro.config;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.xdclass_shiro.domain.Permission;
import net.xdclass.xdclass_shiro.domain.Role;
import net.xdclass.xdclass_shiro.domain.User;
import net.xdclass.xdclass_shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义 Shiro Realm
 *
 * @author zhangsj
 * @date 2020/5/2 9:24
 */
@Slf4j
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 自定义授权，进行权限校验时调用
     *
     * @return org.apache.shiro.authz.AuthorizationInfo
     * @author zhangsj
     * @date 2020/5/2 15:10
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("==> 开始用户授权流程");

        String username = (String) principalCollection.getPrimaryPrincipal();
        User user = userService.findAllUserInfoByUsername(username);

        List<String> roles = new ArrayList<>();
        List<String> permissions = new ArrayList<>();

        List<Role> roleList = user.getRoleList();
        roleList.forEach(role -> {
            roles.add(role.getName());

            List<Permission> permissionList = role.getPermissionList();
            permissionList.forEach(permission -> {
                if (null != permission) {
                    permissions.add(permission.getName());
                }
            });
        });

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermissions(permissions);

        return simpleAuthorizationInfo;
    }

    /**
     * 自定义认证，用户登录的时候使用
     *
     * @param authenticationToken token
     * @return org.apache.shiro.authc.AuthenticationInfo
     * @author zhangsj
     * @date 2020/5/2 15:11
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("==> 开始用户认证流程");

        // 从 token 中获取用户信息，token代表用户输入
        String username = (String) authenticationToken.getPrincipal();

        // 根据用户名查询系统中的用户信息
        User user = userService.findAllUserInfoByUsername(username);
        String password = user.getPassword();
        if (password == null || "".equals(password)) {
            log.error("[{}] 用户不存在", username);
            return null;
        }

        return new SimpleAuthenticationInfo(username, password, this.getClass().getName());
    }
}
